package com.ruoyi.system.controller;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.MingUserconfig;
import com.ruoyi.system.domain.Mynews;
import com.ruoyi.system.domain.MystockName;
import com.ruoyi.system.service.IMingUserconfigService;
import com.ruoyi.system.service.IMystockNameService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.MystockValueD;
import com.ruoyi.system.service.IMystockValueDService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 每天股票价格Controller
 * 
 * @author ruoyi
 * @date 2023-03-04
 */
@RestController
@RequestMapping("/system/d")
public class MystockValueDController extends BaseController
{
    @Autowired
    private IMystockValueDService mystockValueDService;
    @Autowired
    private IMingUserconfigService mingUserconfigService;

    @Autowired
    private IMystockNameService mystockNameService;
    /**
     * 查询每天股票价格列表
     */
    @PreAuthorize("@ss.hasPermi('system:d:list')")
    @GetMapping("/list")
    public TableDataInfo list(MystockValueD mystockValueD)
    {
        startPage();
        List<MystockValueD> list = mystockValueDService.selectMystockValueDList(mystockValueD);
        return getDataTable(list);
    }

    /**
     * 导出每天股票价格列表
     */
    @PreAuthorize("@ss.hasPermi('system:d:export')")
    @Log(title = "每天股票价格", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MystockValueD mystockValueD)
    {
        List<MystockValueD> list = mystockValueDService.selectMystockValueDList(mystockValueD);
        ExcelUtil<MystockValueD> util = new ExcelUtil<MystockValueD>(MystockValueD.class);
        util.exportExcel(response, list, "每天股票价格数据");
    }

    /**
     * 获取每天股票价格详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:d:query')")
    @GetMapping(value = "/query")
    public AjaxResult getInfo()
    {
        AjaxResult ajax = AjaxResult.success();
//        Long userId = 54l;
        SysUser user = SecurityUtils.getLoginUser().getUser();
//        userId = user.getUserId();

//        MingUserconfig mingUserconfig = new MingUserconfig();
//        mingUserconfig.setUserId(userId);
//        String stocks = "";
//        List<MingUserconfig> userConf = mingUserconfigService.selectMingUserconfigList(mingUserconfig);
        MingUserconfig userConf = mingUserconfigService.selectMingUserconfigById(user.getUserconfId());
//        if (userConf!=null && userConf.size() ==1) {
//            MingUserconfig mingConf = userConf.get(0);
        String stocks = userConf.getStock();
//        }
        Map<String, Object> mystockValueDs = new HashMap<String, Object>(2);


        DateTimeFormatter fmDate = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDate today = LocalDate.now();
//        mystockValueDs.put("tradeDate","20230303");


//        LocalDate pro2day = LocalDate.now().minus(2, ChronoUnit.DAYS);
//        System.out.println("2天前:"+pro2day.format(fmDate));

        mystockValueDs.put("tradeDate",today.format(fmDate));

        List codelist = new ArrayList();
        String [] mystocks = stocks.split(",");
        for (int i = 0; i < mystocks.length; i++) {
            codelist.add(mystocks[i]);
        }
        mystockValueDs.put("tsCodeList", codelist);
        List<MystockValueD> list = mystockValueDService.selectMystockValueDLists(mystockValueDs);

        //没有数据 将往前找，直到找到数据
        if (list == null || list.size() == 0) {
            int num =10;
            LocalDate pro1day = null;
            System.out.println("没有数据 将往前找，直到找到数据");
            for (int i = 1; i < num--; i++) {
                pro1day = LocalDate.now().minus(i, ChronoUnit.DAYS);
                System.out.println(i + "天前:" + pro1day.format(fmDate));
                mystockValueDs.put("tradeDate",pro1day.format(fmDate));
                list = mystockValueDService.selectMystockValueDLists(mystockValueDs);
                if (list!=null&&list.size()>0) {
                    System.out.println("找到数据："+pro1day.format(fmDate));
                    break;
                }
            }
        }

        Mynews mynews = new Mynews();
        int stock_num = 9;
        String stockStr = "----股票------开盘--收盘--最高--最低--涨跌幅\n";
        for (MystockValueD mystkD: list) {

            if (stock_num--<0) {
                break;
            }
            /*ts_code	str	股票代码
            trade_date	str	交易日期
            open	float	开盘价
            high	float	最高价
            low	float	最低价
            close	float	收盘价
            pre_close	float	昨收价(前复权)
            change	float	涨跌额
            pct_chg	float	涨跌幅 （未复权，如果是复权请用 通用行情接口 ）
            vol	float	成交量 （手）
            amount	float	成交额 （千元）*/
//            stockStr +=mystkD.getTradeDate()+"-"+mystkD.getTsCode()+"-"+mystkD.getOpen()+"-"+mystkD.getClose()+"-"+mystkD.getHigh()+"-"+mystkD.getLow()+"-"+mystkD.getAmount()+"\n";
            //(label1, "#ff0000 red#,#00ff00 green#,#0000ff blue#")
            String pctChgClo = "";
            if (mystkD.getPctChg().compareTo(BigDecimal.ZERO)>=0) {
                pctChgClo +="#00ff00 ";
            } else {
                pctChgClo +="#ff0000 ";
            }
            BigDecimal bigDecimal = mystkD.getPctChg();
            bigDecimal = bigDecimal.setScale(2, RoundingMode.HALF_UP);

            MystockName mystockName = mystockNameService.selectMystockNameByTsCode(mystkD.getTsCode());
            System.out.println(mystockName.getName().length());
//            System.out.println(mystockName.getName() +" "+formatStr(mystkD.getOpen().toString())+" "+formatStr(mystkD.getClose().toString())+" "+formatStr(mystkD.getHigh().toString())+" "+formatStr(mystkD.getLow().toString())+"  "+pctChgClo+formatStr(bigDecimal.toString())+"#");
            stockStr +=mystockName.getName()+" "+formatStr(mystkD.getOpen().toString())+" "+formatStr(mystkD.getClose().toString())+" "+formatStr(mystkD.getHigh().toString())+" "+formatStr(mystkD.getLow().toString())+"   "+pctChgClo+bigDecimal.toString()+"#\n";
        }
        mynews.setComment(stockStr);
//        if (mynews.getComment().length()>zimujiange_num) {
//            String tmp = processNews(mynews,"*");
//            log.info(String.valueOf(tmp.length()));
//            mynews.setComment(getStringW(stockStr,zimujiange_num));
//            log.info(mynews.getComment());
//        }
        return AjaxResult.success(mynews);
    }

    public String formatStr(String value){
//        System.out.println("需要格式化的值："+value);
        String rtVaule = "";
        if (value.indexOf(".")>=0) {
            String [] tmp = value.split("\\.");
            if(tmp!=null && tmp.length>1) {
                if (tmp[0].length() == 1) {
                    rtVaule += "  " + tmp[0];
                } else {
                    rtVaule += tmp[0];
                }
                rtVaule += ".";
                if (tmp[1].length() == 1) {
                    rtVaule += tmp[1] + "  ";
                } else {
                    rtVaule += tmp[1];
                }
//                System.out.println("`"+rtVaule+"`");
                return rtVaule;
            }
        }
        if (value.length()==2) {
            value += "      ";
        }
        return value;
    }

    /**
     * 新增每天股票价格
     */
    @PreAuthorize("@ss.hasPermi('system:d:add')")
    @Log(title = "每天股票价格", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MystockValueD mystockValueD)
    {
        return toAjax(mystockValueDService.insertMystockValueD(mystockValueD));
    }

    /**
     * 修改每天股票价格
     */
    @PreAuthorize("@ss.hasPermi('system:d:edit')")
    @Log(title = "每天股票价格", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MystockValueD mystockValueD)
    {
        return toAjax(mystockValueDService.updateMystockValueD(mystockValueD));
    }

    /**
     * 删除每天股票价格
     */
    @PreAuthorize("@ss.hasPermi('system:d:remove')")
    @Log(title = "每天股票价格", businessType = BusinessType.DELETE)
	@DeleteMapping("/{tsCodes}")
    public AjaxResult remove(@PathVariable String[] tsCodes)
    {
        return toAjax(mystockValueDService.deleteMystockValueDByTsCodes(tsCodes));
    }
}
